//
//  CJBaseViewController.swift
//  SwiftDemo
//
//  Created by Chris on 2017/6/12.
//  Copyright © 2017年 chris. All rights reserved.
//

import UIKit

class CJBaseViewController: UIViewController {
    
    /// 创建视图的信息
    var visitInfoDictionary: [String: String]?
    
    var tableView: UITableView?
    
    /// 下拉控件
    var refreshControl: UIRefreshControl?
    
    /// 是否上拉加载更多, 只有上拉时,为true, 执行完上拉请求后, 为false
    var isPullUp: Bool = false
    
    /// 自定义导航栏
    lazy var navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.cj_screenWidth(), height: 64))
    
    /// 自定义导航item
    lazy var navItem = UINavigationItem()
    
    /// 导航栏的title
    override var title: String? {
        didSet {
            navItem.title = title
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        CJNetworkManager.sharedManager.userLoginOn ? loadData() : ()
        // 添加登录成功监听
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: NSNotification.Name(rawValue: CJUserLoginSuccessNotification), object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    /// 加载数据
    func loadData() {
        refreshControl?.endRefreshing()
    }
    
    /// 登录
    @objc fileprivate func login() {
        print("login")
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: CJUserShouldLoginInNotification), object: nil)
    }
    
    /// 注册
    @objc fileprivate func register() {
        print("register")
    }
    
    /// 登陆成功
    @objc private func loginSuccess() {
        print("登录成功!")
        
        // 重新设置导航item
        navItem.leftBarButtonItem = nil
        navItem.rightBarButtonItem = nil
        
        // 移除登录视图, 会重新调控制器viewdidload方法
        view = nil
        // 移除监听, 再次调用viewdidload方法会重复注册通知
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK: - 设置界面
extension CJBaseViewController {
    
    /// 设置UI界面
    fileprivate func setupUI() {
        automaticallyAdjustsScrollViewInsets = false
        
        setupNavigationBar()
        CJNetworkManager.sharedManager.userLoginOn ? setupTableView() : setupVisitView()
    }
    
    /// 设置导航条
    private func setupNavigationBar() {
        // 添加导航栏
        view.addSubview(navigationBar)
        navigationBar.items = [navItem]
        // 设置控制器push时, 导航栏渲染颜色
        navigationBar.barTintColor = UIColor.cj_colorWithHex(hex: 0xf6f6f6)
        // 设置导航title文字颜色
        navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.darkGray]
        //设置navigation barbutton的渲染颜色
        navigationBar.tintColor = UIColor.orange
    }
    
    /// 设置tableView和refreshControl
    func setupTableView() {
        
        tableView = UITableView(frame: view.bounds, style: .plain)
        tableView?.delegate = self
        tableView?.dataSource = self
        tableView?.contentInset = UIEdgeInsets(top: navigationBar.bounds.height, left: 0, bottom: tabBarController?.tabBar.bounds.height ?? 49, right: 0)
        tableView?.scrollIndicatorInsets = tableView!.contentInset
        view.insertSubview(tableView!, belowSubview: navigationBar)
        
        refreshControl = UIRefreshControl()
        tableView?.addSubview(refreshControl!)
        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
    }
    
    /// 创建未登录视图
    private func setupVisitView() {
        
        let visitView = CJVisitView(frame: view.bounds)
        
        view.insertSubview(visitView, belowSubview: navigationBar)
        
        guard let visitInfoDict = visitInfoDictionary else {
            return
        }
        visitView.visitInfo = visitInfoDict
        //未登录界面按钮点击
        visitView.loginBtn.addTarget(self, action: #selector(login), for: .touchUpInside)
        visitView.registerBtn.addTarget(self, action: #selector(register), for: .touchUpInside)
        //导航栏登录注册按钮
        navItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(register))
        navItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(login))
    }
}

// MARK: - tableView数据源方法
extension CJBaseViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
    /// 上拉刷新
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        let section = indexPath.section
        
        let sections = tableView.numberOfSections - 1
        
        if section != sections {
            return;
        }
        let row = indexPath.row
        
        let count = tableView.numberOfRows(inSection: section)
        
        if row == count - 1 && !isPullUp {
            print("上拉刷新!")
            isPullUp = true
            loadData()
        }
    }
}
